package com.cro.prison.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cro.prison.dao.TrackDao;
import com.cro.prison.entity.pojo.Depart;
import com.cro.prison.entity.pojo.Device;
import com.cro.prison.entity.pojo.Prisoner;
import com.cro.prison.entity.pojo.Track;
import com.cro.prison.entity.vo.TrackNameVo;
import com.cro.prison.entity.vo.TrackVo;
import com.cro.prison.service.DepartService;
import com.cro.prison.service.DeviceService;
import com.cro.prison.service.PrisonerService;
import com.cro.prison.service.TrackService;
import com.cro.prison.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TrackServiceImpl extends ServiceImpl<TrackDao,Track> implements TrackService {


    @Autowired
    DepartService departService;
    @Autowired
    DeviceService deviceService;

    @Autowired
    PrisonerService prisonerService;

    @Autowired
    TrackDao trackDao;
    @Override
    public List<TrackVo> getTrackListById(Long id) {

        Prisoner prisoner = prisonerService.getById(id);
        String name = prisoner.getName();

        List<Depart> departList = departService.list();
        Map<Long, Depart> departMap = departList.stream().collect(Collectors.toMap(Depart::getId, d -> d));
        List<Device> deviceList = deviceService.list();
        Map<Long, Device> deviceMap = deviceList.stream().collect(Collectors.toMap(Device::getId, d -> d));

        List<Track> trackList = this.baseMapper.selectList(new QueryWrapper<Track>().eq("prisoner_id", id));
        List<TrackVo> resultList = trackList.stream().map(item -> {
            TrackVo trackVo = new TrackVo();
            trackVo.setDate(DateUtils.detailFormat(item.getDate()));
            trackVo.setSrc(item.getSrc());
            Long deviceId = item.getDeviceId();
            //根据deviceId获取位置信息
            //根据deviceId获取departId
            Long departId = deviceMap.get(item.getDeviceId()).getDepartId();
            Depart currentDepart = departMap.get(departId);
            String place = "";
            if(currentDepart!=null){
                place = currentDepart.getName();
                while(currentDepart.getPid()!=0){
                    currentDepart = departMap.get(currentDepart.getPid());
                    place = currentDepart.getName() +"-" + place;
                }
            }
            trackVo.setLocation(place);
            trackVo.setName(name);
            trackVo.setNumber(item.getId().toString());
            return trackVo;
        }).collect(Collectors.toList());
        return resultList;
    }

    @Override
    public List<TrackNameVo> getTrackNames() {
        return trackDao.getTrackNames();
    }
}
